package com.ksc.util;

import com.ksc.entity.Sender;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmailUtil {

    // 发送邮件
    public static boolean sendEmail(Sender sender, String to, String title, String content) {
        Properties props = new Properties();
        props.put("mail.smtp.host", sender.getHost());
        props.put("mail.smtp.auth", sender.isAuth());
        props.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密，如果需要的话
        props.put("mail.smtp.port", "587"); // SMTP端口，视你的邮件服务器而定

        // 创建验证器
        Authenticator auth = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(sender.getSender(), sender.getCode());
            }
        };

        // 获取会话实例
        Session session = Session.getInstance(props, auth);

        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(sender.getSender()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(title);
            message.setText(content);

            // 发送邮件
            Transport.send(message);

            System.out.println("邮件发送成功！");
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }
}
